#include <stdio.h>

#include <dbDefs.h>
#include <registryFunction.h>
#include <subRecord.h>
#include <epicsExport.h>
#include <wiringPi.h>

#define IOC_LED 17
#define BI_LED 27
#define BI 12
int Debug,old_value,value,num = 1,led = 1;
static long mySubInit(subRecord *precord)
{
	wiringPiSetupGpio();

  	// pin mode ..(INPUT, OUTPUT, PWM_OUTPUT, GPIO_CLOCK)
  	// set pin 17 to input
  	pinMode(IOC_LED, OUTPUT);
        digitalWrite(IOC_LED,HIGH);

        pinMode(BI_LED, OUTPUT);
	pinMode(BI,INPUT);
    
  	// pull up/down mode (PUD_OFF, PUD_UP, PUD_DOWN) => down
  	pullUpDnControl(BI, PUD_UP);

	old_value = !digitalRead(BI);
	return 0;
}

static long mySubProcess(subRecord *precord)
{
    
    value = !digitalRead(BI);
    if(old_value != value){
        precord->val = value;
        if(Debug){
            printf("The value is changed !!!\tNow Level: %s\n",(value==1?"HIGH":"LOW"));
            if(num == 10){
                digitalWrite(IOC_LED,led = !led);
                num = 1;
            }
            else{
                num ++;
            }
            if(digitalRead(BI_LED) == value){
                digitalWrite(BI_LED,value);
            }
            old_value = value;
		}
        else{
            if(digitalRead(BI_LED) != 0){
		        digitalWrite(BI_LED,0);
        }
	}
	return 0;
}


/* Register these symbols for use by IOC code: */
epicsExportAddress(int, Debug);
epicsRegisterFunction(mySubInit);
epicsRegisterFunction(mySubProcess);
